package com.sskj.gcc.ui.fragment;


import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.LanguageUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.gcc.R;
import com.sskj.gcc.bean.game.GameCommunitiesListBean;
import com.sskj.gcc.bean.game.GameIndexBean;
import com.sskj.gcc.presenter.game.GameFragmentPresenter;
import com.sskj.gcc.ui.activity.MainActivity;
import com.sskj.gcc.ui.dialog.GameBottomDialog;
import com.sskj.gocoin.m.bean.UserInfo;
import com.sskj.gocoin.v.activity.PayPwdSettingActivity;
import com.sskj.gocoin.v.activity.SecurityCenterActivity;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.util.TipUtil;
import com.tencent.bugly.crashreport.CrashReport;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import pl.droidsonroids.gif.AnimationListener;
import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;

import static com.sskj.gcc.ui.dialog.GameBottomDialog.GAME_ACTIVE;
import static com.sskj.gcc.ui.dialog.GameBottomDialog.GAME_EXCHANGE;
import static com.sskj.gcc.ui.dialog.GameBottomDialog.GAME_FOOD;
import static com.sskj.gcc.ui.dialog.GameBottomDialog.GAME_MALL;
import static com.sskj.gcc.ui.dialog.GameBottomDialog.GAME_NOTIFICATION;
import static com.sskj.gcc.ui.dialog.GameBottomDialog.GAME_PACKAGE;

@Route(path = RConfig.APP_GAME)
public class GameFragment extends GameBaseFragment {

    @BindView(R.id.iv_bird)
    GifImageView ivBird;
    @BindView(R.id.ll_notification)
    LinearLayout llNotification;
    @BindView(R.id.ll_active)
    LinearLayout llActive;
    @BindView(R.id.ll_exchange)
    LinearLayout llExchange;
    @BindView(R.id.ll_mall)
    LinearLayout llMall;
    @BindView(R.id.ll_package)
    LinearLayout llPackage;
    @BindView(R.id.ll_food)
    LinearLayout llFood;
    @BindView(R.id.ll_food_number)
    LinearLayout llFoodNumber;
    @BindView(R.id.tv_food_time)
    TextView tvFoodTime;
    @BindView(R.id.tv_food_number)
    TextView tvFoodNumber;
    @BindView(R.id.tv_egg_number)
    TextView tvEggNumber;
    @BindView(R.id.pb_egg)
    ProgressBar pbEgg;
    @BindView(R.id.tv_egg_progress)
    TextView tvEggProgress;
    Unbinder unbinder;
    @BindView(R.id.iv_app_home_game_egg_home)
    GifImageView ivAppHomeGameEggHome;
    @BindView(R.id.iv_game_rice)
    ImageView ivGameRice;

    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.tv_bird_msg)
    TextView tvBirdMsg;


    private UserInfo userInfo;
    private GameIndexBean gameIndexBean;
    private GifDrawable app_home_game_egg_home_anim;
    private CountDownTimer countDownTimerRice;
    private int state13Rice = 0;

    @Override
    public int getLayoutId() {
        return R.layout.app_fragment_game;
    }

    @Override
    public GameFragmentPresenter getPresenter() {
        return new GameFragmentPresenter();
    }

    @Override
    public void initView() {
        LanguageUtil.changeAppLanguage(getActivity(), LanguageUtil.getAppLocale(App.INSTANCE), true);
        RxBus.getDefault().register(this);
        ARouter.getInstance().inject(this);

        //公告
        ClickUtil.click(llNotification, () -> {
            GameBottomDialog.start(this.getActivity(), GAME_NOTIFICATION);
        });
        //动态
        ClickUtil.click(llActive, () -> {
            GameBottomDialog.start(this.getActivity(), GAME_ACTIVE);
        });
        //兑换
        ClickUtil.click(llExchange, () -> {
            if (userInfo != null && userInfo.getConfig().getPayment_password_set() != 1) {
                TipUtil.getTip(getActivity(), com.sskj.gocoin.common.App.INSTANCE.getString(com.sskj.gocoin.R.string.strMainActivity218), new TipUtil.OnTipSure() {
                    @Override
                    public void onSure() {
                        startActivity(new Intent(getActivity(), SecurityCenterActivity.class));
                    }
                }).show();
                return;
            }
            GameBottomDialog.start(this.getActivity(), GAME_EXCHANGE);
        });
        //商城
        ClickUtil.click(llMall, () -> {
            ToastUtil.showShort(getString(R.string.str_temporarily_opened));
//            GameBottomDialog.start(this.getActivity(), GAME_MALL);
        });
        //背包
        ClickUtil.click(llPackage, () -> {
            GameBottomDialog.start(this.getActivity(), GAME_PACKAGE);
        });
        //食物
        ClickUtil.click(llFood, () -> {
            GameBottomDialog.start(this.getActivity(), GAME_FOOD);
        });
        //孔雀
        ClickUtil.click(ivBird, () -> {
//            GameBottomDialog.start(this.getActivity(), GAME_BIRDDETAIL);
        });
        //当前拥有的食物数
        ClickUtil.click(llFoodNumber, () -> {
            //提交过程中不能再点击
            ToastUtil.showShort(getString(R.string.str_temporarily_opened));
//            mPresenter.eatfeedoff();
        });

        //收蛋
        ClickUtil.click(ivAppHomeGameEggHome, () -> {
            mPresenter.getEggs();
        });
        getInitHttpData();

        countDownTimerRice = new CountDownTimer(Integer.MAX_VALUE, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                if (gameIndexBean != null) {
                    state13Rice--;
                    if (state13Rice < 0) {
                        countDownTimerRice.cancel();
                        ivGameRice.setImageResource(R.drawable.app_home_game_rice_empty);
                        tvFoodTime.setText("0");
                    }
                    tvFoodTime.setText(secToTime(state13Rice));
                }
            }

            @Override
            public void onFinish() {

            }
        };

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getInitHttpData();
            }
        });

    }

    void getInitHttpData() {
        if (countDownTimerRice != null) {
            countDownTimerRice.cancel();
        }
        mPresenter.requestGameIndex();
        mPresenter.requestUserInfo();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (countDownTimerRice != null) {
            countDownTimerRice.cancel();
        }
    }

    @Override
    public void requestUserInfoSuccess(UserInfo userInfo) {
        super.requestUserInfoSuccess(userInfo);
        this.userInfo = userInfo;
    }

    @Override
    public void onError(String msg) {
        super.onError(msg);
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setRefreshing(false);
        }
    }

    public void onGameIndexSuccess(GameIndexBean gameIndexBean) {
        if (!isVisible() || isHidden()) {
            return;
        }
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setRefreshing(false);
        }
        this.gameIndexBean = gameIndexBean;
        //state10 孔雀状态 1正常状态 2进食状态 3饥饿状态 4死亡状态
        if ("2".equals(gameIndexBean.getState10())) {
            ivBird.setImageResource(R.drawable.image_game_bird_2);
        } else if ("3".equals(gameIndexBean.getState10())) {
            ivBird.setImageResource(R.drawable.image_game_bird_3);
        } else if ("4".equals(gameIndexBean.getState10())) {
            ivBird.setImageResource(R.drawable.image_game_bird_4);
        } else {
            ivBird.setImageResource(R.drawable.image_game_bird_1);
        }

        //食料余额数量
        tvFoodNumber.setText(String.format(getString(R.string.strMainActivityGame00017), gameIndexBean.getState7()));
        //state5 待产蛋数量 蛋上显示的数量
        tvEggNumber.setText(TextUtils.isEmpty(gameIndexBean.getState5()) ? "0" : gameIndexBean.getState5());
        //state11产蛋进度条 100 = 100%
        pbEgg.setProgress(TextUtils.isEmpty(gameIndexBean.getState11()) ? 0 : Integer.parseInt(gameIndexBean.getState11()));
        tvEggProgress.setText((TextUtils.isEmpty(gameIndexBean.getState11()) ? 0 : gameIndexBean.getState11()) + "%");

        //state13  食料进食完成时间 如果为 0 则今天未进食 如果进食则显示吃完时间
        if (TextUtils.isEmpty(gameIndexBean.getState13()) || "0".equals(gameIndexBean.getState13())) {
            ivGameRice.setImageResource(R.drawable.app_home_game_rice_empty);
            tvFoodTime.setText("0");
        } else {
            state13Rice = Integer.parseInt(gameIndexBean.getState13());
            if (countDownTimerRice != null) {
                countDownTimerRice.start();
            }
            ivGameRice.setImageResource(R.drawable.app_home_game_rice);
        }

        if (TextUtils.isEmpty(gameIndexBean.getState12())) {
            tvBirdMsg.setVisibility(View.GONE);
        } else {
            tvBirdMsg.setVisibility(View.VISIBLE);
            tvBirdMsg.setText(gameIndexBean.getState12());

            GradientDrawable background0 = new GradientDrawable();
            background0.setCornerRadius(40);
            background0.setColor(Color.parseColor("#F9DC43"));
            background0.setStroke(1, Color.parseColor("#8F6E1E"));//设置描边
            tvBirdMsg.setTextColor(Color.parseColor("#8F6E1E"));
            tvBirdMsg.setBackground(background0);

        }

    }

    public void onEatFeedOffSuccess(String success) {
        getInitHttpData();
        ToastUtil.showShort(success);
    }

    @Override
    public void onGetEggsSuccess(String msg) {
        super.onGetEggsSuccess(msg);
        if (!GameFragment.this.isHidden()) {
            getInitHttpData();
            ToastUtil.showShort(msg);
            try {
                if (app_home_game_egg_home_anim == null) {
                    app_home_game_egg_home_anim = new GifDrawable(getResources(), R.drawable.app_home_game_egg_home_anim);
                    app_home_game_egg_home_anim.setLoopCount(1);
                    app_home_game_egg_home_anim.addAnimationListener(new AnimationListener() {
                        @Override
                        public void onAnimationCompleted(int loopNumber) {
                            app_home_game_egg_home_anim.seekTo(0);
                        }
                    });
                    ivAppHomeGameEggHome.setImageDrawable(app_home_game_egg_home_anim);
                } else {
                    app_home_game_egg_home_anim.start();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Subscribe(code = RxBusCode.GAME_SHOP_CONFIRM, threadMode = ThreadMode.MAIN)
    public void gameShopConfirm(GameCommunitiesListBean gameCommunitiesListBean) {

        MaterialDialog dialog = new MaterialDialog.Builder(getActivity())
                .customView(R.layout.dialog_game_pay_confirm, false)
                .autoDismiss(false)
                .cancelable(true)
                .show();
        View customeView = dialog.getCustomView();

        ((TextView) customeView.findViewById(R.id.tv_name)).setText(gameCommunitiesListBean.getName());
        ((TextView) customeView.findViewById(R.id.tv_price)).setText(gameCommunitiesListBean.getPrice() + " USDT");
        ((TextView) customeView.findViewById(R.id.tv_number)).setText("X " + gameCommunitiesListBean.getNums());

        ClickUtil.click(customeView.findViewById(R.id.tvSure), () -> {
            EditText et_input_password = (EditText) customeView.findViewById(R.id.et_input_password);
            if (TextUtils.isEmpty(et_input_password.getText().toString())) {
                ToastUtil.showShort(et_input_password.getHint().toString());
                return;
            }
            mPresenter.placeOrder(gameCommunitiesListBean.getId() + "", et_input_password.getText().toString());
            dialog.dismiss();
        });
        ClickUtil.click(customeView.findViewById(R.id.tvCancel), () -> {
            dialog.dismiss();
        });
        dialog.show();
    }


    @Subscribe(code = RxBusCode.GAME_REFRESH, threadMode = ThreadMode.MAIN)
    public void game_refresh() {
        getInitHttpData();
    }

    @Override
    public void placeOrderSuccess(String msg) {
        super.placeOrderSuccess(msg);
        ToastUtil.showShort(msg);
    }

    /**
     * 秒转换小时-分-秒analytics/util/DateUtil.java
     *
     * @param seconds 秒为单位 比如..600秒
     * @return 比如...2小时3分钟52秒
     */
    public String secToTime(int seconds) {
        int hour = seconds / 3600;
        int minute = (seconds - hour * 3600) / 60;
        int second = (seconds - hour * 3600 - minute * 60);

        StringBuffer sb = new StringBuffer();
        if (hour > 0) {
            sb.append(hour + getString(R.string.strMainActivityGame0008));
        }
        if (minute > 0) {
            sb.append(minute + getString(R.string.strMainActivityGame0009));
        }
        if (second > 0) {
            sb.append(second + getString(R.string.strMainActivityGame00010));
        }
        if (second == 0) {
            sb.append(getString(R.string.strMainActivityGame00011));
        }
        return sb.toString();
    }


}
